package com.apache.rpc.service.impl;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.rpc.entity.SystemConfig;
import com.apache.rpc.manager.SystemConfigManager;
import com.apache.tools.DateUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class SystemConfigManagerImpl implements SystemConfigManager {
    protected Logger log = Logger.getLogger(getClass());
    protected IDao systemConfigDao;

    protected final String entityName = "com.apache.rpc.entity.SystemConfig";

    public void setSystemConfigDao(IDao systemConfigDao) {
        this.systemConfigDao = systemConfigDao;
    }

    public String saveInfo(ParamsVo<SystemConfig> vo) throws BusinessException {
        SystemConfig config = vo.getObj();
        //定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
        String cacheKey = "";
        MethodParam param = new MethodParam("SystemConfig", cacheKey, "", entityName);
        config.setUpdateTime(DateUtils.Now.toLong());
        param.setVaule(config);
        if (systemConfigDao.insert(param)) {
            setChacheInfo(config, "");
            return config.getFileName();
        }
        return "";
    }

    public boolean editInfo(ParamsVo<SystemConfig> vo) throws BusinessException {
        SystemConfig config = vo.getObj();
        if (Validator.isNotNull(config.getFileName())) {
            String cacheKey = "";
            config.setUpdateTime(DateUtils.Now.toLong());
            MethodParam param = new MethodParam("SystemConfig", cacheKey, "", entityName);
            param.setVaule(config);
            boolean mark = systemConfigDao.edit(param);
            if (mark) {
                setChacheInfo(config, "");
            }
            return mark;
        }
        return false;
    }

    public boolean deleteInfo(ParamsVo<SystemConfig> vo) throws BusinessException {
        String infoId = vo.getInfoId();
        if (Validator.isNull(infoId)) {
            return false;
        }
        String cacheKey = "";
        //String cacheKey = "interfaceRegister_" + infoId;
        String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
        MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
        param.setInfoId(infoId);
        SystemConfig info = (SystemConfig) systemConfigDao.selectById(param);
        if (Validator.isEmpty(info)) {
            return false;
        }
        boolean flag = false;
        param.setVaule(info);//此处需要先将状态值赋值为删除状态
        if ("false".equals(mark)) {//逻辑删除
            param.setKey("SystemConfig");
            flag = systemConfigDao.edit(param);
        } else {
            param.setParams("fileName", infoId);
            param.setDelete(true);
            flag = systemConfigDao.delete(param);
            if (flag) {
                setChacheInfo(null, infoId);
            }
        }
        return flag;
    }

    private void setChacheInfo(SystemConfig config, String fileName) {
        if (Validator.isNotNull(fileName)) {
            LoadCacheFactory.getInstance().getCacheManager("").removeCacheObject(fileName);
            LoadCacheFactory.getInstance().getCacheManager("")
                    .removeCacheObject(fileName + "_flag");
        } else {
            InputStream stream = null;
            try {
                fileName = config.getFileName();
                if (fileName.indexOf(".properties") != -1) {
                    Properties prop = new Properties();
                    if (Validator.isNotNull(config.getConfingText())) {
                        stream = IOUtils.toInputStream(config.getConfingText());
                        prop.load(stream);
                    }
                    LoadCacheFactory.getInstance().getCacheManager("")
                            .createCacheObject(fileName, prop);
                } else {
                    LoadCacheFactory.getInstance().getCacheManager("")
                            .createCacheObject(fileName, config.getConfingText());
                }
                LoadCacheFactory.getInstance().getCacheManager("")
                        .createCacheObject(fileName + "_flag", config.getUpdateTime() + "");
            } catch (Exception e) {
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }
    }

    public Object getInfoById(ParamsVo<SystemConfig> vo) {
        String infoId = vo.getInfoId();
        String cacheKey = "";
        if (Validator.isNull(infoId)) {
            return null;
        }
        MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
        param.setInfoId(infoId);
        return systemConfigDao.selectById(param);
    }

    public Object execute(ParamsVo<SystemConfig> vo) {
        String key = vo.getMethodKey();
        if ("initCache".equalsIgnoreCase(key)) {
            initCache();
        }
        return null;
    }

    private void initCache() {
        MethodParam param = new MethodParam("ByProperty", "", "", entityName);
        List<SystemConfig> list = systemConfigDao.select(param);
        log.info("配置信息加载start");
        if (Validator.isEmpty(list))
            return;
        for (int i = 0; i < list.size(); i++) {
            setChacheInfo(list.get(i), "");
            log.info((i+1)+"）配置对象->"+ list.get(i).getFileName());
        }
        LoadCacheFactory.getInstance().getCacheManager("").createCacheObject("is.open.cache", "T");
        SystemTools.getInstance().getValue("");
        log.info("初始化[配置信息]条数据到缓存完成！");
    }

    public Page getPageInfo(ParamsVo<SystemConfig> vo) {
        MethodParam param = setMethodParams(vo, 2);
        int pageSize = Integer
                .valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
        int pageIndex = Integer
                .valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
        param.setPageIndex(pageIndex);
        param.setPageSize(pageSize);
        Page page = systemConfigDao.pageSelect(param);
        return page;
    }

    @SuppressWarnings("unchecked")
    public List<SystemConfig> getList(ParamsVo<SystemConfig> vo) {
        MethodParam param = setMethodParams(vo, 2);
        return systemConfigDao.select(param);
    }

    public long countInfo(ParamsVo<SystemConfig> vo) {
        MethodParam param = setMethodParams(vo, 1);
        return systemConfigDao.count(param);
    }

    private MethodParam setMethodParams(ParamsVo<SystemConfig> vo, int type) {
        String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
        StringBuffer sb = new StringBuffer(systemConfigDao.getSql(type));
        MethodParam param = new MethodParam(methodKey, "", "", entityName);
        SystemConfig config = vo.getObj();
        if (Validator.isEmpty(config))
            return param;
        if (Validator.isNotNull(config.getFileName())) {
            sb.append(" and fileName = :fileName");
            param.setParams("fileName", config.getFileName());
        }
        param.setSqlStr(sb.toString());
        return param;
    }

}
